/* typehints:start */
import { GameRoot } from "../root";
import { Task } from "./task";
import { Npc } from "../npcs/npc";
/* typehints:end */

import { createLogger } from "../../core/utils/logging";
import TaskModules from "./get_task";

const logger = createLogger('game/game_task')

export class GameTask {
	constructor(root) {
		/** @type {GameRoot} */
		this.root = root;

		this.tasks = {};
	}

	initialize() {
		Object.keys(TaskModules).map(key => {
			this.tasks[key] = new TaskModules[key](this.root);
		})
	}

	/**
	 *
	 * @param {*} id
	 * @returns {Task}
	 */
	getTask(id) {
		let task = this.tasks[id];
		if (!task) {
			logger.warn("不存在的任务ID:", id);
			return;
		}

		return task;
	}

	/**
	 * 获取所有的任务对象
	 * @returns
	 */
	getAllTask() {
		let tasks = [];

		for (let i = 0; i < this.root.worldData.tasks.length; i++) {
			let worldDataTask = this.root.worldData.tasks[i];
			let task = this.getTask(worldDataTask.id);
			if (task && !worldDataTask.complete) {
				tasks.push(task);
			}
		}

		return tasks;
	}

	/**
	 * 是否接取过这个任务
	 * @param {*} data {id, repeat}
	 * @returns
	 */
	isPickTask(id) {
		let task = this.getTask(id);
		if (!task) return false;

		for (let i = this.root.worldData.tasks.length - 1; i >= 0; i--) {
			let worldDataTask = this.root.worldData.tasks[i];

			if (worldDataTask.id == id) {
				return worldDataTask;
			}
		}

		return false;
	}

	add(id) {
		let task = this.getTask(id);
		if (!task) return;

    let pickTask = this.isPickTask(id);
		if (pickTask && !pickTask.complete) {
			this.root.message(
        'alert',
				`任务<${task.getTitle()}>正在进行`
			);
			return;
		}

		let worldTask = this.isPickTask(id);

		if (worldTask) {
			worldTask.complete = false;
			worldTask.num++;
		} else {
			this.root.worldData.tasks.push({
				id,
				time: this.root.worldData.time,
				complete: false,
				num: 1,

        created_time: new Date(),
        updated_time: new Date()
			});
		}

		let text = `接取任务<${task.getTitle()}>`;
		this.root.message(
			"alert",
			text
		);
		this.root.message('log', '系统', text, 'log');
		this.root.hud.parts.taskPage.drawTask();
		this.root.saveWorldData();
	}

	complete(id, npc) {
		let task = this.getTask(id);
		if (!task) return;

		if (!this.isPickTask(id)) {
			this.root.message(
				"alert",
				`未接受任务<${task.getTitle()}>`
			);
			return;
		}

    let pickTask = this.isPickTask(id);
    pickTask.complete = this.root.worldData.time;
    pickTask.updated_time = new Date();

    task.completedCb(npc);

		let text = `任务<${task.getTitle()}>完成`;
		this.root.message(
			"alert",
			text
		);
		this.root.message('log', '系统', text, 'log');
		this.root.hud.parts.taskPage.drawTask();
		this.root.saveWorldData();
	}
}